<template>
  <div class="inline-flex items-center">
    <el-button
        type="primary"
        class="ml-4 flex items-center"
        @click="dialogVisible = true"
    >
      <i class="el-icon-magic-stick mr-1"></i>
      智能填写
    </el-button>

    <el-dialog
        v-model="dialogVisible"
        title="智能信息填写"
        width="500px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
    >
      <div class="mb-4">
        <div class="flex items-center mb-2">
          <el-alert
              type="info"
              :closable="false"
              show-icon
          >
            <template #title>
              <span class="text-sm">支持粘贴参考文献格式文本，自动识别论文信息</span>
            </template>
          </el-alert>
        </div>

        <div class="mt-4">
          <p class="text-gray-600 text-sm mb-2">支持的引用格式：</p>
          <p class="text-gray-500 text-xs bg-gray-50 p-2 rounded">
            GB/T格式：[1]作者,等.标题[J/OL].期刊,页码[日期].URL
          </p>
        </div>

        <el-input
            type="textarea"
            v-model="citationText"
            :rows="4"
            placeholder="请在此粘贴参考文献格式文本"
            class="mt-4"
        ></el-input>
      </div>

      <template #footer>
        <div class="flex justify-end">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button
              type="primary"
              @click="handleSmartFill"
              :disabled="!citationText"
          >
            开始识别
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'

const dialogVisible = ref(false)
const citationText = ref('')
const emit = defineEmits(['update:form'])

// 判断引用格式类型
const detectCitationType = (text) => {
  if (text.match(/^\[\d+\]/)) {
    return 'GB/T'
  } else if (text.includes('et al.')) {
    return 'MLA'
  } else if (text.includes('&') && text.match(/$$\d{4}$$/)) {
    return 'APA'
  }
  return 'GB/T' // 默认格式
}

// 解析作者信息的函数
const parseAuthors = (text, format) => {
  let authors = []
  let cleanText = text

  switch (format) {
    case 'GB/T':
      // 移除引用编号并获取作者部分
      cleanText = text.replace(/^\[\d+\]/, '').split('.')[0]
      authors = cleanText.split(',').filter(author => !author.includes('等'))
      break

    case 'MLA':
      // 处理MLA格式：作者, et al.
      cleanText = text.split('et al.')[0]
      authors = cleanText.split(',').map(a => a.trim()).filter(Boolean)
      break

    case 'APA':
      // 处理APA格式：作者1,作者2,&作者3
      cleanText = text.split('(')[0]
      authors = cleanText.split(/[,&]/).map(a => a.trim()).filter(Boolean)
      break
  }

  return authors.map((name, index) => ({
    rank: (index + 1).toString(),
    name: name.trim(),
    identity: index === 0 ? '第一作者' : `第${index + 1}作者`,
    isCorresponding: index === 0,
    isCoFirstAuthor: false,
    institution: ''
  }))
}

// 解析年份的函数
const parseYear = (text, format) => {
  switch (format) {
    case 'GB/T':
      // 首先尝试匹配完整日期格式 [YYYY-MM-DD]
      const fullDateMatch = text.match(/\[(\d{4}-\d{2}-\d{2})\]/)
      if (fullDateMatch) {
        return fullDateMatch[1] // 返回完整的日期字符串
      }
      // 如果没有完整日期，则尝试匹配年份
      const yearMatch = text.match(/\b(20\d{2})\b/)
      return yearMatch ? `${yearMatch[1]}-01-01` : ''

    case 'MLA':
      // MLA格式通常在文末
      const mlaMatch = text.match(/\b(20\d{2})\b/)
      return mlaMatch ? `${mlaMatch[1]}-01-01` : ''

    case 'APA':
      // APA格式：(YYYY)
      const apaMatch = text.match(/$$(\d{4})$$/)
      return apaMatch ? `${apaMatch[1]}-01-01` : ''

    default:
      return ''
  }
}

// 解析标题的函数
const parseTitle = (text, format) => {
  switch (format) {
    case 'GB/T':
      const gbMatch = text.match(/\.(.*?)\[/)
      return gbMatch ? gbMatch[1].trim() : ''

    case 'MLA':
      const mlaMatch = text.match(/et al\.(.*?)\./)
      return mlaMatch ? mlaMatch[1].trim() : ''

    case 'APA':
      const apaMatch = text.match(/\)\.(.*?)\./)
      return apaMatch ? apaMatch[1].trim() : ''

    default:
      return ''
  }
}

// 解析期刊信息的函数
const parseJournal = (text, format) => {
  switch (format) {
    case 'GB/T':
      const gbMatch = text.match(/\[(J|J\/OL)\]\.([^,]+)/)
      return gbMatch ? gbMatch[2].trim() : ''

    case 'MLA':
      const mlaMatch = text.match(/\.(.*?)\s+\d/)
      return mlaMatch ? mlaMatch[1].trim() : ''

    case 'APA':
      const apaMatch = text.match(/\.(.*?),\s*\d+/)
      return apaMatch ? apaMatch[1].trim() : ''

    default:
      return ''
  }
}

// 解析卷期号的函数
const parseVolumeAndIssue = (text, format) => {
  switch (format) {
    case 'GB/T':
      const gbMatch = text.match(/(\d+)$$(\d+)$$/)
      return {
        volume: gbMatch ? gbMatch[1] : '',
        issue: gbMatch ? gbMatch[2] : ''
      }

    case 'MLA':
      // MLA格式通常不明确标注卷期
      return { volume: '', issue: '' }

    case 'APA':
      const apaMatch = text.match(/,\s*(\d+)$$(\d+)$$/)
      return {
        volume: apaMatch ? apaMatch[1] : '',
        issue: apaMatch ? apaMatch[2] : ''
      }
  }
}

// 解析页码的函数
const parsePages = (text, format) => {
  switch (format) {
    case 'GB/T':
      const gbMatch = text.match(/,\s*(\d+)[-~](\d+)(?:\[|\.|$)/)
      return gbMatch ? `${gbMatch[1]}~${gbMatch[2]}` : ''

    case 'MLA':
      const mlaMatch = text.match(/\s+(\d+)[-~](\d+)\./)
      return mlaMatch ? `${mlaMatch[1]}~${mlaMatch[2]}` : ''

    case 'APA':
      const apaMatch = text.match(/,\s*(\d+)[-~](\d+)\./)
      return apaMatch ? `${apaMatch[1]}~${apaMatch[2]}` : ''

    default:
      return ''
  }
}

// 解析DOI或URL的函数
const parseDOI = (text) => {
  // 尝试匹配DOI
  const doiPattern = /doi\.org\/([^\s]+)/i
  const doiMatch = text.match(doiPattern)

  if (doiMatch) {
    return doiMatch[1]
  }

  // 尝试匹配URL中的DOI部分
  const urlDoiPattern = /\/(\d+\.\d+\/[^\s\.]+)/
  const urlDoiMatch = text.match(urlDoiPattern)

  if (urlDoiMatch) {
    return urlDoiMatch[1]
  }

  return ''
}

// 智能填写处理函数
const handleSmartFill = () => {
  if (!citationText.value) {
    ElMessage.warning('请先粘贴参考文献文本')
    return
  }

  try {
    const text = citationText.value
    const format = detectCitationType(text)

    // 构建要更新的表单数据
    const formData = {
      title: parseTitle(text, format),
      authorInfo: parseAuthors(text, format),
      journalName: parseJournal(text, format),
      publishDate: parseYear(text, format),
      pageRange: parsePages(text, format),
      doi: parseDOI(text),
      volumeNumber: parseVolumeAndIssue(text, format).volume,
      issueNumber: parseVolumeAndIssue(text, format).issue,
      paperType: '期刊论文',
      researchField: '科研(自科)',
    }

    // 发出更新表单的事件
    emit('update:form', formData)

    ElMessage.success(`使用${format}格式解析完成`)
    dialogVisible.value = false
    citationText.value = ''
  } catch (error) {
    console.error('解析错误:', error)
    ElMessage.error('解析失败，请检查输入格式是否正确')
  }
}
</script>

<style scoped>
:deep(.el-dialog__body) {
  padding-top: 10px;
}
</style>
